package promote.brozen.netty.protocol.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author Brozen
 * @date 2020/9/29 4:35 PM
 * @email brozen@qq.com
 */
@Slf4j
public class NettyHttpServerDispatcher extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        if (!msg.decoderResult().isSuccess()) {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            log.info("解析Http请求失败.");
            return;
        }

        log.info("请求方法 {} {}", msg.method().name(), msg.uri());

        HttpHeaders headers = msg.headers();
        headers.forEach(entry -> log.info("Header {} : {}", entry.getKey(), entry.getValue()));

        String body = msg.content().toString(StandardCharsets.UTF_8);
        log.info("请求体： {}", body);

        sendMsg(ctx, "OK, I got it. your body is :" + body);
    }


    private void sendMsg(ChannelHandlerContext ctx, String msg) {
        byte[] data = msg.getBytes(StandardCharsets.UTF_8);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        HttpUtil.setContentLength(response, data.length);
        response.content().writeBytes(data);

        ctx.write(response);
        ctx.flush();
    }


    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
        ctx.write(response);
        ctx.flush();
    }

}
